﻿@using DCMS.Web.Extensions;
@using DCMS.Web.Framework;
@using DCMS.Web.Framework.UI;
@using DCMS.ViewModel.Models.Report;
@using DCMS.Core.Domain.Common;

@model VisitStoreListModel

<section id="content_wrapper">
	<!-- Start: Topbar-Dropdown -->
	<div id="topbar-dropmenu">
		@await Html.PartialAsync("_ToolBox")
	</div>
	<!-- End: Topbar-Dropdown -->
	<!-- Start: Topbar -->
	<header id="topbar">
		<div class="topbar-left">
			<ol class="breadcrumb">
				<li class="crumb-active">
					<a href="#">报表</a>
				</li>
				<li class="crumb-icon">
					<a href="@Url.RouteUrl("HomePage")">
						<span class="glyphicon glyphicon-home"></span>
					</a>
				</li>
				<li class="crumb-link">
					<a href="#">员工报表</a>
				</li>
				<li class="crumb-trail">业务员拜访记录</li>
			</ol>
		</div>
		<div class="topbar-right">
			<div class="ml15 ib va-m" id="toggle_sidemenu_r">
				<a href="#" class="pl5">
					<i class="fa fa-sign-in fs22 text-primary"></i>
					<span class="badge badge-hero badge-danger">3</span>
				</a>
			</div>
		</div>
	</header>
	<!-- End: Topbar -->
	<!-- Begin: Content -->
	<section id="content" class="formSection">

		<div class="special-alerts">
			<div class="alert alert-danger light alert-dismissable" id="alert-demo-2" style="display: none;">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
				<i class="fa fa-info pr10"></i>
				<strong>您没有被授权此操作!</strong>
			</div>
		</div>

		<div class="row">
			<div class="col-md-12">
				<form asp-action="BusinessUserVisitingRecord" asp-controller="VisitStore" method="get" id="formSearch" novalidate="novalidate">
					<div class="panel panel-default" id="panel0">
						<div class="panel-heading">
							<span class="glyphicon glyphicon-search"></span> 高级搜索
							<a class="btn btn-default btn-sm pull-right m5 mrn p5 pbn" id="AdvancedSearch"><i class="fa fa-angle-double-right"></i></a>
						</div>
						<div class="panel-body p10">
							<div class="row">

								<div class="col-sm-2">
									<dcms-select asp-for="BusinessUserId" asp-items="@Model.BusinessUsers" asp-default="业务员" />
								</div>
								<div class="col-sm-2">
									<div class="input-group">
										<input asp-for="TerminalId" type="hidden" />
										<input asp-for="TerminalName" class="form-control" placeholder="客户..." />
										<span class="input-group-btn">
											<button id="btn_search_customer" type="button" class="btn btn-default">
												<span class="glyphicon glyphicon-search"></span>
											</button>
										</span>
									</div>
								</div>

								<div class="col-sm-2">
									<dcms-select asp-for="DistrictId" asp-items="@Model.Districts" asp-default="片区" />
								</div>

								<div class="col-sm-2">
									<dcms-select asp-for="ChannelId" asp-items="@Model.Channels" asp-default="渠道" />
								</div>

								<div class="col-sm-2">
									<dcms-select asp-for="VisitTypeId" asp-items="@Model.VisitTypes" asp-default="拜访类型" />
								</div>
								<div class="col-sm-2">
									<dcms-editor asp-for="SigninDateTime" placeholder="签到时间..." />
								</div>
							</div>

							<div class="row mt10">
								<div class="col-sm-2">
									<dcms-editor asp-for="SignOutDateTime" placeholder="签退时间..." />
								</div>

								<div class="col-sm-10">
									<button id="btn_query" type="submit" class="btn btn-primary btn-block">
										<span class="glyphicon glyphicon-search mr5" aria-hidden="true"></span>查询
									</button>
								</div>
							</div>
						</div>
					</div>
				</form>

				<div class="panel">
					<div class="panel-heading">
						<div class="panel-title">
							<span class="glyphicon glyphicon-tasks"></span> 报表
						</div>
					</div>
                    <div class="panel-body p10">

                        <div id="toolbar" class="btn-group mb10">
                            <a href="@Url.Action("BusinessUserVisitingRecord")" class="btn btn-default btn-sm mr5">
                                <span class="glyphicon glyphicon-refresh mr5"></span>重置
                            </a>
                            <a class="btn btn-info btn-sm mr5" id="btn_export">
                                <span class="glyphicon glyphicon-export mr5" aria-hidden="true"></span>导出
                            </a>

                            <a class="btn btn-info btn-sm mr5" id="btn_dp_export">
                                <span class="glyphicon glyphicon-export mr5" aria-hidden="true"></span>导出陈列图片
                            </a>
                        </div>

                        <table class="table table-striped table-bordered table-hover">
                            <tr>
                                @*<th class="text-left" rowspan="2"><input id="checkAll" type="checkbox" /></th>
        <th class="text-left" rowspan="2"><div class="th-inner">业务员</div></th>
        <th class="text-left" rowspan="2"><div class="th-inner">客户</div></th>
        <th class="text-left" rowspan="2"><div class="th-inner">客户编码</div></th>
        <th class="text-left" rowspan="2"><div class="th-inner">状态</div></th>
        <th class="text-center" rowspan="2"><div class="th-inner">签到时间</div></th>
        <th class="text-center" rowspan="2"><div class="th-inner">在店时间</div></th>
        <th class="text-left" rowspan="2"><div class="th-inner">线路</div></th>
        <th class="text-right" rowspan="2"><div class="th-inner">未拜访天数</div></th>
        <th class="text-center" rowspan="2"><div class="th-inner">门店图片</div></th>
        <th class="text-center" rowspan="2"><div class="th-inner">陈列图片</div></th>
        <th class="text-center" rowspan="2"><div class="th-inner">地图</div></th>
        <th class="text-center" colspan="4"><div class="th-inner">达成金额</div></th>
        <th class="text-left" rowspan="2"><div class="th-inner">备注</div></th>*@
                                <th class="text-left"><input id="checkAll" type="checkbox" /></th>
                                <th class="text-left"><div class="th-inner">业务员</div></th>
                                <th class="text-left"><div class="th-inner">客户</div></th>
                                <th class="text-left"><div class="th-inner">客户编码</div></th>
                                <th class="text-left"><div class="th-inner">状态</div></th>
                                <th class="text-center"><div class="th-inner">签到时间</div></th>
                                <th class="text-center"><div class="th-inner">在店时间</div></th>
                                <th class="text-center"><div class="th-inner">门店图片</div></th>
                                <th class="text-center"><div class="th-inner">陈列图片</div></th>
                                <th class="text-center"><div class="th-inner">地图</div></th>
                                <th class="text-center"><div class="th-inner">是否下单</div></th>
                                <th class="text-left"><div class="th-inner">备注</div></th>
                            </tr>
                            @*<tr>
                                <th class="text-right"><div class="th-inner">销订金额</div></th>
                                <th class="text-right"><div class="th-inner">退订金额</div></th>
                                <th class="text-right"><div class="th-inner">销售金额</div></th>
                                <th class="text-right"><div class="th-inner">退货金额</div></th>
                            </tr>*@
                            @{
                                if (Model.Items != null && Model.Items.Count > 0)
                                {
                                    @foreach (var item in Model.Items)
                                    {
                        <tr>
                            <td><input id="@item.Id" class="cbSelect text-left" name="checkbox" type="checkbox" /></td>
                            <td class="text-left">@item.BusinessUserName</td>
                            <td class="text-left">@item.TerminalName</td>
                            <td class="text-left">@item.CodeNumber</td>
                            <td class="text-left" style="color:#12c24c;">@item.VisitTypeName</td>
                            <td class="text-center ">@item.SigninDateTime</td>
                            <td class="text-center">@((item.OnStoreStopSeconds/3600)?.ToString("00") +":" + ((item.OnStoreStopSeconds % 3600)/60)?.ToString("00") + ":" + (item.OnStoreStopSeconds % 60)?.ToString("00"))</td>
                            @*<td class="text-left">@item.LineName</td>*@
                            @*<td class="text-right">@item.NoVisitedDays</td>*@
                            <td class="text-center">
                                @Html.Raw(item.DoorheadPhotos.Count > 0 ?
                                    "<a style='color:#2c850d;text-decoration:none;' href='javascript:void(0)' onclick='showImage(\"door\", " + item.Id + " )' >查看</a>" : null)
                            </td>
                            <td class="text-center">
                                @Html.Raw(item.DisplayPhotos.Count > 0 ?
                                    "<a style='color:#2c850d;text-decoration:none;' href='javascript:void(0)' onclick='showImage(\"display\", " + item.Id + ")' >查看</a>" : null)
                            </td>
                            <td class="text-center">
                                <span>
                                    <a href="#" onclick="showMap(@item.Latitude,@item.Longitude)" class="grid-location-btn" style="color:#0092DC;">
                                        <i class="fa fa-map-marker fa-lg" aria-hidden="true"></i>
                                    </a>
                                </span>
                            </td>
                            @*<td class="text-right">￥ @((item.SaleAmount ?? 0).ToString("0.00"))</td>
        <td class="text-right">￥ @((item.SaleOrderAmount ?? 0).ToString("0.00"))</td>
        <td class="text-right">￥ @((item.ReturnAmount ?? 0).ToString("0.00"))</td>
        <td class="text-right">￥ @((item.ReturnOrderAmount ?? 0).ToString("0.00"))</td>*@
                            <td class="text-left">@Html.Raw(item.IsCreateOrder?"是":"否")</td>
                            <td class="text-left">@item.Remark</td>
                            <td class="text-center displayPath" style="display:none">
                                <div class="zoom-gallery-@item.Id">
                                    @foreach (var photo in item.DisplayPhotos)
                                    {
                                        if (photo.DisplayPath != null && photo.DisplayPath != "")
                                        {
                                            <a title="陈列照片" href="/VisitStore/ShowImage?url=@photo.DisplayPath" class="boxer_display_@item.Id" data-source="/VisitStore/ShowImage?url=@photo.DisplayPath">
                                                <img src="/VisitStore/ShowImage?url=@photo.DisplayPath" alt="">
                                            </a>

                                        }
                                    }
                                    @foreach (var photo in item.DoorheadPhotos)
                                    {
                                        if (photo.StoragePath != null && photo.StoragePath != "")
                                        {

                                            <a title="门头照片" href="/VisitStore/ShowImage?url=@photo.StoragePath" class="boxer_door_@item.Id" data-source="/VisitStore/ShowImage?url=@photo.StoragePath">
                                                <img src="/VisitStore/ShowImage?url=@photo.StoragePath" alt="">
                                            </a>
                                        }
                                    }
                                </div>
                            </td>
                        </tr>
                                    }
                                }
                                else
                                {
                                    <tr class="no-records-found"><td class="text-center" colspan="18">没有找到匹配的记录</td></tr>
                                }
                            }
                        </table>

                        @{
                            var pager = Html.Pager(Model.PagingFilteringContext).QueryParam("pagenumber");
                        }

                        @if (!pager.IsEmpty())
                        {
                            <div class="fixed-table-pagination" style="display: block;">
                                @Html.Raw(pager.ToString())
                            </div>
                        }
                    </div>
				</div>
			</div>
		</div>

		<div id="progress"><span></span></div>
	</section>
	<!-- End: Content -->
</section>


@{
    await Html.RenderPartialAsync("_MapModal", new ViewDataDictionary(ViewData) { { "formId", "MapForm" }, { "showSave", "true" } });
    //客户选择
    await Html.RenderPartialAsync("_ModalForm", new ViewDataDictionary(ViewData) { { "formId", "TerminalSelectForm" }, { "modalWindow", "TerminalSelectModalWindow" }, { "windowWidth", "1000px" }, { "showSave", "true" } });
}


@section CurPageScripts
{

	<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=bB75lKXKUHnI2o0dbND5ktWFSWOEg5Tv"></script>
	<script type="text/javascript" src="https://api.map.baidu.com/library/AreaRestriction/1.2/src/AreaRestriction_min.js"></script>
	<script type="text/javascript" src="https://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js"></script>
	<script type="text/javascript">
		var map = new BMap.Map("allmap");    // 创建Map实例
		var geoc = new BMap.Geocoder();

		jQuery(document).ready(function () {

			"use strict";

			// Init Theme Core
			Core.init();

			// Init Demo JS
			Demo.init();

			//权限提示
			if ($(this).getUrlQueryString("Authorize") == "noAuthorize") {
				$('#alert-demo-2').fadeToggle();
				setTimeout(function () {
					$('#alert-demo-2').fadeToggle();
				}, 3000);
			}

			//高级搜索
			$("#panel0 #AdvancedSearch").click(function () {
				var ico = $(this).find(".fa");
				if (ico.hasClass('fa-angle-double-right'))
					ico.removeClass("fa-angle-double-right").addClass("fa-angle-double-down");
				else
					ico.removeClass("fa-angle-double-down").addClass("fa-angle-double-right");
				$("#panel0").find(".panel-body").toggleClass("hidden fadeIn");
			});

			//客户搜索
			$(document).on('click', "#btn_search_customer", function () {
				var actionUrl = "/Terminal/AsyncSearchSelectPopup";
				$(this).showModalV2($("#TerminalSelectModalWindow"), actionUrl, { ids: "" }, "选择终端", $("#TerminalSelectForm"), function (rows) { });
			});

			window.operateEventsPopTerminal = {
				'click .rowSelect': function (e, value, row, index) {
					try {
						$("#TerminalId").val(row.Id);
						$("#TerminalName").val(row.Name);
						$('#TerminalSelectModalWindow').modal('hide');
					}
					catch (err) {
						console.log(err);
						$(this).showToastr(err);
						return;
					}
				}
			};

			map.enableScrollWheelZoom(true);
			// 初始化地图,设置中心点坐标和地图级别
			map.centerAndZoom(new BMap.Point(108.953044, 34.351147), 15);
			map.addControl(new BMap.ScaleControl());
			map.addControl(new BMap.OverviewMapControl());
			map.addControl(new BMap.MapTypeControl());

			//鼠标点击监听
			map.addEventListener("click", function (e) {
				//通过点击百度地图，可以获取到对应的point, 由point的lng、lat属性就可以获取对应的经度纬度
				var pt = e.point;
				geoc.getLocation(pt, function (rs) {
					//addressComponents对象可以获取到详细的地址信息
					var addComp = rs.addressComponents;
					var site = addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber;
					$("#site").val(site);
				});
			});

			//防止重复查询
			var queryNumber = 1;
			$("#btn_query").click(function () {
				if (queryNumber > 1) {
					return false;
				}
				queryNumber = queryNumber + 1;
			});

			//用户修改客户名称，将客户Id置零
			$("#TerminalName").bind("change", function () {
				$("#TerminalId").val(0);
			});


		});

		function showImage(flag, id) {
			if (flag == "door")
			{
				////图片预览
				//$('.boxer_door_'+ id).boxer({
    //                requestKey: 'door',
				//	labels: {
				//		close: "Close",
				//		count: "/",
				//		next: "Next",
				//		previous: "Prev",
				//	},
				//	height: 800
				//});
                $('.zoom-gallery-' + id).magnificPopup({
                    delegate: 'a',
                    type: 'image',
                    closeOnContentClick: false,
                    closeBtnInside: false,
                    mainClass: 'mfp-with-zoom mfp-img-mobile',
                    image: {
                        verticalFit: true,
                        titleSrc: function (item) {
                            return item.el.attr('title') + ' &middot; <a class="image-source-link" href="' + item.el.attr('data-source') + '" target="_blank">image source</a>';
                        }
                    },
                    gallery: {
                        enabled: true
                    },
                    zoom: {
                        enabled: true,
                        duration: 300, // don't foget to change the duration also in CSS
                        opener: function (element) {
                            return element.find('img');
                        }
                    }
				});
                $('.boxer_door_' + id)[0].click();
			}
			else
			{
				//图片预览
				//$('.boxer_display_'+ id).boxer({
    //                requestKey: 'display',
				//	labels: {
				//		close: "Close",
				//		count: "/",
				//		next: "Next",
				//		previous: "Prev"
    //                },
    //                height: 800
				//});
                $('.zoom-gallery-' + id).magnificPopup({
                    delegate: 'a',
                    type: 'image',
                    closeOnContentClick: false,
                    closeBtnInside: false,
                    mainClass: 'mfp-with-zoom mfp-img-mobile',
                    image: {
                        verticalFit: true,
                        titleSrc: function (item) {
                            return item.el.attr('title') + ' &middot; <a class="image-source-link" href="' + item.el.attr('data-source') + '" target="_blank">image source</a>';
                        }
                    },
                    gallery: {
                        enabled: true
                    },
                    zoom: {
                        enabled: true,
                        duration: 300, // don't foget to change the duration also in CSS
                        opener: function (element) {
                            return element.find('img');
                        }
                    }
                });
				$('.boxer_display_' + id)[0].click();
			}
		};

		function showMap(lat, lng) {
			map.clearOverlays();
			var pt = new BMap.Point(lng, lat);
			var marker = new BMap.Marker(pt);
			map.addOverlay(marker);
			setTimeout(function () {
				map.panTo(pt);
			}, 1000);

			// 百度地图API功能
			$('#MapForm').modal('show');
		}
		//获取全部选中
		//默认导出按钮不可用
		$("#btn_dp_export").attr("disabled", true);
		$("#checkAll").click(function () {
			if ($("#checkAll").prop("checked")) {
				$("input[name='checkbox']").prop("checked", true);
				$("#btn_dp_export").attr("disabled", false);
			} else {
				$("input[name='checkbox']").prop("checked", false);
				$("#btn_dp_export").attr("disabled", true);
			}
		});


		//单个选择
		$(".cbSelect").click(function () {
			if ($("input[type=checkbox]:checked:checked").length == 1) {
				if ($(this).prop("checked")) {
					$(this).prop("checked", true);
					$("#checkAll").prop("checked", false)
					$("#btn_dp_export").attr("disabled", false);
				}
				else {
					$(this).prop("checked", false);
					$("#checkAll").prop("checked", true);
					$("#btn_dp_export").attr("disabled", true);
				}
			}
			else {
				if ($(this).prop("checked")) {
					$(this).prop("checked", true);
					$("#checkAll").prop("checked", true);
					$("#btn_dp_export").attr("disabled", false);
				}
				else {
					$(this).prop("checked", false);
					$("#checkAll").prop("checked", false);
					if ($("input[type=checkbox]:checked:checked").length < 1) {
						$("#btn_dp_export").attr("disabled", true);
					} else {
						$("#btn_dp_export").attr("disabled", false);
					}

				}

			}
		});


		//导出陈列产品图片
		$("#btn_dp_export").click(function () {
			$("#btn_dp_export").attr("disabled", true);
			var arr = new Array();
			//获取选中后对应的陈列图片URL
			$("input[type=checkbox]:checked:checked").each(function () {
				var imgUrl = $(this).closest("tr").find(".displayPath").find("img").attr("src");
				if (imgUrl != "" && imgUrl != undefined) {
					arr.push(imgUrl);
				}
			});
			var currtime = new Date().Format("yyyyMMddHHmmss");
			if (arr.length > 0) {
				var zip = new JSZip();
				// 创建images文件夹
				var imgFolder = zip.folder("displayPhoto");
				//判断加载了几张图片的标识
				let flag = 0
				var mydate = new Date();
				for (let i = 0; i < arr.length; i++) {
					getBase64(arr[i]).then(function (base64) {
						base64 = base64.split('base64,')[1]
						imgFolder.file(i + '.jpg', base64, { base64: true })
						if (flag === arr.length - 1) {
							zip.generateAsync({ type: "blob" }).then((blob) => {
								//保存图片并压缩
								saveAs(blob, "displayPhoto_" + currtime + ".zip")
								$("#btn_dp_export").attr("disabled", false);
							})
						}
						flag++
					}, function (err) {
						//打印异常信息
						console.log(err);
						$(this).showToastr('图片导出异常，请联系管理员！');
						return;
					});


				}
				function getBase64(img) {
					function getBase64Image(img, width, height) {
						//width、height调用时传入具体像素值，控制大小 ,不传则默认图像大小
						var canvas = document.createElement("canvas");
						canvas.width = width ? width : img.width;
						canvas.height = height ? height : img.height;

						var ctx = canvas.getContext("2d");
						ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
						var dataURL = canvas.toDataURL();
						return dataURL;
					}
					var image = new Image();
					image.crossOrigin = '*';
					image.src = img;
					var deferred = $.Deferred();
					if (img) {
						image.onload = function () {
							//将base64传给done上传处理
							deferred.resolve(getBase64Image(image));
						}
						return deferred.promise();
					}
				}
			}
			else {
				$(this).showToastr('目前没有可以导出的图片');
				return;

			}
		});

		Date.prototype.Format = function (fmt) {
			var o = {
				"M+": this.getMonth() + 1, //月份
				"d+": this.getDate(), //日
				"H+": this.getHours(), //小时
				"m+": this.getMinutes(), //分
				"s+": this.getSeconds(), //秒
				"q+": Math.floor((this.getMonth() + 3) / 3), //季度
				"S": this.getMilliseconds() //毫秒
			};
			if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
			for (var k in o)
				if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			return fmt;
		}
        //导出
        $("#btn_export").click(function () {
            window.location.href = "/VisitStore/ExportBusinessUserVisitingRecord?businessUserId=" + $("#BusinessUserId").val() + "&terminalId=" + $("#TerminalId").val() + "&terminalName=" + $("#TerminalName").val() + "&districtId=" + $("#DistrictId").val() + "&channelId=" + $("#ChannelId").val() + "&visitTypeId=" + $("#VisitTypeId").val() + "&signinDateTime=" + $("#SigninDateTime").val() + "&signOutDateTime=" + $("#SignOutDateTime").val();
        });

	</script>
}

